package com.ruoyi.common.utils.wxapi;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.project.thirdservice.constant.WxConst;
import org.apache.commons.codec.binary.Base64;


/**
 * 封装对外访问方法
 */
@SuppressWarnings("all")
public class WXCore {

    private static final JSONObject EMPTY = new JSONObject();

    private static final WxapiAESUtil AES = new WxapiAESUtil();

    /**
     * 解密数据
     *
     * @return
     * @throws Exception
     */
    public static JSONObject decrypt(String appId, String encryptedData, String sessionKey, String iv) {
        try {
            byte[] resultByte = AES.decrypt(Base64.decodeBase64(encryptedData),
                    Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if (null != resultByte && resultByte.length > 0) {
                JSONObject theJSONObject = JSONObject
                        .parseObject(new String(WxPKCS7Encoder.decode(resultByte)));
                String decryptAppid = theJSONObject
                        .getJSONObject(WxConst.WATERMARK).getString(WxConst.APPID);
                if (!appId.equals(decryptAppid)) {
                    return EMPTY;
                }
                return theJSONObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return EMPTY;
        }
        return EMPTY;
    }


    public static void main(String[] args) {
        String appId = "wx95899997b27985ae";
        String encryptedData = "9uxmOdTnCdr2+PWeM8JDC2BcO9MEy4LmwjOyWrApzOqWqQLF3VjNXKU/xmrMkdm83mHrHrNnpmpAakV7iUMhTuPi7t/Xb1oEUlGEi1EuVlWjOuDmwCCxKTpUHzCJ/x+Ttz9h4gqgNXQO6ywv+02uwK+PRMity923DTJkbhXXcZCO/iE095y+zOYt8O9BGIKroHM/5KwAdpOPPh4/Yn/vcP/0NyVhV23nfcyZAA2Avs3F2ufNt/s16996/2UYbVvNTBosC/DfgAwhOVeRQJqSiGpPOGEer43JPlFnFGlrlfstnMvoHvN2YjpNKD9M1Zs2Bzr0kaYNAk6wsyIQ5Yvz/Sn7Kk1ywJGs6P5Vv5ydr+beHuP3KHUYMgBHmvoiYYqxiMc4Uw4iviqvDKZ7pxIoOwpR4/6x3IEG+Eh9+PDgQyma+3oVv6tQUSMFEiEEURWMFwqlNUZe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oUapbbbdAPn+JJ3x/buQinRiUDcU6i0xqBXot/vBcJAjs2+tBzJ3SZCq1aMwiTywG6meyK+YQedg6g2Rs/0qhH36v+HyczZT+2nxG53OvWsF/86NdwTtbBg+ZpRqkjdhHR";
        String sessionKey = "ALnnWnoWiP065eO4fJKBKA==";
        String iv = "qv+UFmdqOLPKggwcUEtt5g==";
        System.out.println(decrypt(appId, encryptedData, sessionKey, iv).toJSONString());
    }
}